package io.gitee.devaper.starlight.common.util

/**
 * 这里存放与Servlet相关的工具
 */

import io.gitee.devaper.starlight.common.holder.*
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.MediaType
import java.nio.charset.StandardCharsets

/**
 * 将对象序列化并写到响应中
 *
 * @param data 数据内容
 * @param request 请求对象
 */
fun HttpServletResponse.write(data: Any, request: HttpServletRequest? = null) {
    // future 传递了请求对象支持自动内容协商
    contentType = MediaType.APPLICATION_JSON_VALUE
    characterEncoding = StandardCharsets.UTF_8.name()
    ObjectMapperHolder.get().writeValue(writer, data)
}